<template>
  <el-dialog
    title="导入学生到教学任务"
    v-model="visible"
    width="60%"
    :before-close="handleClose"
  >
    <div class="student-import-container">
      <div class="header-info" v-if="teachingMission">
        <h3>课程：{{ teachingMission.courseName }}</h3>
        <p>学期：{{ teachingMission.termName }}</p>
      </div>
      
      <el-tabs v-model="activeTab">
        <el-tab-pane label="从行政班级导入" name="class">
          <div class="tab-content">
            <p>从以下行政班级批量导入学生：</p>
            
            <el-transfer
              v-model="selectedClasses"
              :data="availableClasses"
              :titles="['可选队次', '已选队次']"
              :props="{
                key: 'id',
                label: 'name'
              }"
              filterable
              filter-placeholder="请输入队次名称"
              @change="handleClassChange">
            </el-transfer>
            
            <div class="selected-info" v-if="currentClassStudents.length > 0">
              <el-alert
                title="以下学生将被添加到教学任务"
                type="info"
                :closable="false"
                show-icon>
              </el-alert>
              
              <el-table 
                :data="currentClassStudents" 
                max-height="250"
                style="width: 100%; margin-top: 10px;"
              >
                <el-table-column prop="studentId" label="学号" width="120"></el-table-column>
                <el-table-column prop="name" label="姓名" width="120"></el-table-column>
                <el-table-column prop="className" label="队次"></el-table-column>
                <el-table-column prop="majorName" label="专业"></el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="选择单个学生" name="student">
          <div class="tab-content">
            <el-form :inline="true" class="student-search-form">
              <el-form-item label="学号">
                <el-input v-model="studentSearch.studentId" placeholder="请输入学号"></el-input>
              </el-form-item>
              <el-form-item label="姓名">
                <el-input v-model="studentSearch.name" placeholder="请输入姓名"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchStudents">搜索</el-button>
                <el-button @click="resetStudentSearch">重置</el-button>
              </el-form-item>
            </el-form>
            
            <el-table
              :data="paginatedStudents"
              style="width: 100%"
              max-height="250"
              @selection-change="handleStudentSelectionChange"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="studentId" label="学号" width="120" resizable></el-table-column>
              <el-table-column prop="name" label="姓名" width="120" resizable></el-table-column>
              <el-table-column prop="className" label="队次" resizable></el-table-column>
              <el-table-column prop="majorName" label="专业" resizable></el-table-column>
            </el-table>
            
            <div class="pagination" v-if="allSearchResults.length > 0">
              <el-pagination
                background
                layout="total, prev, pager, next"
                :total="totalStudents"
                :page-size="pageSize"
                :current-page="currentPage"
                @current-change="handlePageChange">
              </el-pagination>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      
      <div class="import-stats" v-if="selectedStudents.length > 0">
        <el-alert
          :title="`已选择 ${selectedStudents.length} 名学生`"
          type="success"
          :closable="false"
          show-icon>
        </el-alert>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="importStudents" :disabled="selectedStudents.length === 0">
          导入 ({{ selectedStudents.length }})
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, onMounted, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { studentApi } from '@/api/student'
import { classApi } from '@/api/base-data'
import { teachingMissionApi } from '@/api/teaching-mission'

export default {
  name: 'StudentImportDialog',
  props: {
    modelValue: {
      type: Boolean,
      required: true
    },
    teachingMission: {
      type: Object,
      required: false,
      default: () => null
    }
  },
  emits: ['update:modelValue', 'imported'],
  
  setup(props, { emit }) {
    // 对话框可见性
    const visible = computed({
      get: () => props.modelValue,
      set: (val) => emit('update:modelValue', val)
    })
    
    // 标签页相关
    const activeTab = ref('class')
    
    // 行政班级导入相关
    const availableClasses = ref([])
    const selectedClasses = ref([])
    const currentClassStudents = ref([])
    
    // 学生搜索相关
    const studentSearch = reactive({
      studentId: '',
      name: ''
    })
    const searchedStudents = ref([])
    const allSearchResults = ref([]) // 存储所有搜索结果
    const selectedStudents = ref([])
    const selectedStudentIds = ref([]) // 仅存储ID，用于检查重复
    const totalStudents = ref(0)
    const currentPage = ref(1)
    const pageSize = 10
    
    // 获取所有行政班级
    const fetchClasses = async () => {
      try {
        if (!props.teachingMission) {
          console.warn('教学任务不存在，无法获取班级列表')
          return
        }
        
        const response = await classApi.getAllClasses()
        availableClasses.value = response || []
      } catch (error) {
        console.error('获取班级列表失败:', error)
        ElMessage.error('获取班级列表失败')
      }
    }
    
    // 根据班级获取学生
    const fetchStudentsByClass = async (classId) => {
      try {
        const response = await studentApi.getStudentsByClass(classId)
        return response || []
      } catch (error) {
        console.error(`获取班级(ID=${classId})学生失败:`, error)
        ElMessage.error('获取班级学生失败')
        return []
      }
    }
     // 计算分页后的学生数据
    const paginatedStudents = computed(() => {
      const start = (currentPage.value - 1) * pageSize
      const end = start + pageSize
      return allSearchResults.value.slice(start, end)
    })
    
    // 搜索学生
    const searchStudents = async () => {
      try {
        // 验证教学任务
        if (!props.teachingMission) {
          ElMessage.warning('教学任务信息不完整，无法搜索学生')
          return
        }
        
        // 这里应该调用后端API进行搜索，这里模拟一个简单的搜索
        const response = await studentApi.getAllStudents()
        
        let results = response || []
        
        // 本地过滤
        if (studentSearch.studentId) {
          results = results.filter(s => s.studentId.includes(studentSearch.studentId))
        }
        
        if (studentSearch.name) {
          results = results.filter(s => s.name.includes(studentSearch.name))
        }
        
        allSearchResults.value = results
        totalStudents.value = results.length
        currentPage.value = 1 // 重置到第一页
      } catch (error) {
        console.error('搜索学生失败:', error)
        ElMessage.error('搜索学生失败')
      }
    }
    
    // 重置学生搜索
    const resetStudentSearch = () => {
      studentSearch.studentId = ''
      studentSearch.name = ''
      allSearchResults.value = []
      currentPage.value = 1
    }
    
    // 班级变化处理
    const handleClassChange = async (value) => {
      currentClassStudents.value = []
      
      // 获取每个选中班级的学生
      for (const classId of selectedClasses.value) {
        const students = await fetchStudentsByClass(classId)
        
        // 将学生添加到当前列表，避免重复
        for (const student of students) {
          if (!selectedStudentIds.value.includes(student.id)) {
            selectedStudents.value.push(student)
            selectedStudentIds.value.push(student.id)
            currentClassStudents.value.push(student)
          }
        }
      }
    }
    
    // 学生选择变化处理
    const handleStudentSelectionChange = (selection) => {
      // 处理新选择的学生
      for (const student of selection) {
        if (!selectedStudentIds.value.includes(student.id)) {
          selectedStudents.value.push(student)
          selectedStudentIds.value.push(student.id)
        }
      }
      
      // 处理取消选择的学生
      const selectionIds = selection.map(s => s.id)
      const removedStudents = paginatedStudents.value.filter(
        s => !selectionIds.includes(s.id) && selectedStudentIds.value.includes(s.id)
      )
      
      for (const student of removedStudents) {
        const index = selectedStudentIds.value.indexOf(student.id)
        if (index !== -1) {
          selectedStudentIds.value.splice(index, 1)
          selectedStudents.value = selectedStudents.value.filter(s => s.id !== student.id)
        }
      }
    }
    
    // 分页处理
    const handlePageChange = (page) => {
      currentPage.value = page
    }
    
    // 导入学生
    const importStudents = async () => {
      if (selectedStudents.value.length === 0) {
        ElMessage.warning('请选择要导入的学生')
        return
      }
      
      if (!props.teachingMission) {
        ElMessage.warning('教学任务信息不完整，无法导入学生')
        return
      }
      
      try {
        // 构建请求数据
        const data = {
          teachingMissionId: props.teachingMission.id,
          studentIds: selectedStudents.value.map(s => s.id)
        }
        
        // 这里应该调用后端API进行导入
        await teachingMissionApi.addStudentsToTeachingMission(
          props.teachingMission.id,
          selectedStudents.value.map(s => s.id)
        )
        
        const importedCount = selectedStudents.value.length;
        ElMessage.success(`成功导入 ${importedCount} 名学生到教学任务`)
        emit('imported', importedCount)
        handleClose()
      } catch (error) {
        console.error('导入学生失败:', error)
        ElMessage.error('导入学生失败')
      }
    }
    
    // 关闭对话框
    const handleClose = () => {
      // 直接更新visible值
      visible.value = false
      // 重置状态
      activeTab.value = 'class'
      selectedClasses.value = []
      currentClassStudents.value = []
      resetStudentSearch()
      selectedStudents.value = []
      selectedStudentIds.value = []
    }
    
    onMounted(() => {
      // 只有当对话框显示且教学任务存在时才获取班级信息
      if (visible.value && props.teachingMission) {
        fetchClasses()
      }
    })
    
    // 监听 teachingMission 变化，重新获取数据
    watch(() => props.teachingMission, (newVal) => {
      if (newVal && visible.value) {
        fetchClasses()
        // 重置状态
        activeTab.value = 'class'
        selectedClasses.value = []
        currentClassStudents.value = []
        resetStudentSearch()
        selectedStudents.value = []
        selectedStudentIds.value = []
      }
    })
    
    // 监听对话框可见性变化
    watch(() => visible.value, (newVal) => {
      if (newVal && props.teachingMission) {
        fetchClasses()
      }
    })
    
    return {
      visible,
      activeTab,
      availableClasses,
      selectedClasses,
      currentClassStudents,
      studentSearch,
      paginatedStudents,
      allSearchResults,
      selectedStudents,
      totalStudents,
      currentPage,
      pageSize,
      handleClassChange,
      searchStudents,
      resetStudentSearch,
      handleStudentSelectionChange,
      handlePageChange,
      importStudents,
      handleClose
    }
  }
}
</script>

<style scoped>
.student-import-container {
  margin-bottom: 20px;
}

.header-info {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.header-info h3 {
  margin: 0 0 5px 0;
  font-size: 18px;
}

.header-info p {
  margin: 0;
  color: #666;
}

.tab-content {
  padding: 10px 0;
  min-height: 300px;
}

.selected-info {
  margin-top: 20px;
}

.student-search-form {
  margin-bottom: 15px;
}

.pagination {
  margin-top: 15px;
  text-align: right;
}

.import-stats {
  margin-top: 20px;
}

.el-transfer {
  margin-top: 15px;
}
</style>
